import db from "../db";

export default defineEventHandler(async (event) => {
  const sql = `SELECT 
        parent.category_id AS parent_id,
        parent.category_name AS parent_name,
        child.category_id AS child_id,
        child.category_name AS child_name
        FROM category parent
        LEFT JOIN category child ON parent.category_id = child.parent_id
        WHERE parent.parent_id IS NULL
        ORDER BY parent.category_id, child.category_id;
    `;
  try {
    const [rows]: [any[], any[]] = await db.query(sql);
    // 转换为父类数组结构
    const categories = rows.reduce((acc: any[], row: any) => {
      // 查找是否已有该父分类
      let parent = acc.find((item) => item.category_id === row.parent_id);
      if (!parent) {
        // 如果父分类不存在，则创建一个新父分类对象
        parent = {
          category_id: row.parent_id,
          category_name: row.parent_name,
          children: [],
        };
        acc.push(parent);
      }
      // 如果有子分类，则加入父分类的 children 数组
      if (row.child_id) {
        parent.children.push({
          category_id: row.child_id,
          category_name: row.child_name,
        });
      }
      return acc;
    }, []);
    return {
      code: 1,
      message: "成功",
      data: categories,
    };
  } catch (error) {
    console.error(error);
    return {
      code: 500,
      message: "服务器错误",
    };
  }
});
